package com.universal.frame.appupdate;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.universal.frame.R;
import com.universal.frame.generalutils.ApkUtil;
import com.universal.frame.generalutils.Constants;
import com.universal.frame.generalutils.FileUtils;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.LogUtils;
import com.universal.frame.generalutils.NetWorkUtil;
import com.universal.frame.generalutils.SharedPreferencesUtil;

import java.io.File;

public class UpdateAppDialog extends Dialog {

    public UpdateAppDialog(Context context, final String isnew,final String content,final String url, int flg) {
        super(context, R.style.widget_dialog_style);
        // TODO Auto-generated constructor stub
        this.initDialog(context, isnew,content,url, flg);
    }

    private void initDialog(final Context context, final String isnew,final String content,final String url, int flg) {
        View view = LayoutInflater.from(context).inflate(R.layout.app_update_dialog, null, true);

        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        dialogWindow.setAttributes(lp);

        this.setCanceledOnTouchOutside(false);
        this.setCancelable(false);
        this.setContentView(view);

        TextView tvNewVer = (TextView) view.findViewById(R.id.tv_new_version);
        TextView tvCurrentVer = (TextView) view.findViewById(R.id.tv_current_version);
        TextView tvMsg = (TextView) view.findViewById(R.id.tv_update_msg);
        Button btnNot = (Button) view.findViewById(R.id.btn_not_now);
        Button btnUpdate = (Button) view.findViewById(R.id.btn_update_now);
        View lineView = (View) view.findViewById(R.id.line_dialog_btn_view);

        if (flg == 1) {
            btnNot.setVisibility(View.GONE);
            lineView.setVisibility(View.GONE);
        }

        tvNewVer.setText(content);
//        tvMsg.setText(item.update_log);

        long fileSize = FileUtils.getFileSize(GeneralUtil.getAPKSaveFilePath(context, isnew));    //存在手机的文件大小
        long currentFileSize = GeneralUtil.str2Long(SharedPreferencesUtil.getString(context, Constants.SP_FIELD_APP_FILE_SIZE, ""), 0);    //下载更新的文件大小

        LogUtils.i("AppUtils", "fileSize>>>" + fileSize + "   currentFileSize>>>>" + currentFileSize);
        final boolean isFileSize = fileSize == currentFileSize ? true : false;

        final boolean isAPKExist = FileUtils.isFileExist(GeneralUtil.getAPKSaveFilePath(context, isnew));
        if (isAPKExist && isFileSize) {
            btnNot.setText(context.getResources().getString(R.string.text_app_update_dialog_not_install));
            btnUpdate.setText(context.getResources().getString(R.string.text_app_update_dialog_now_install));
            tvCurrentVer.setText(context.getResources().getString(R.string.text_app_update_dialog_new_version_download));
            btnNot.setVisibility(View.VISIBLE);
            lineView.setVisibility(View.VISIBLE);
            btnUpdate.setBackgroundResource(R.drawable.material_dialog_button_yes);

        } else {
            tvCurrentVer.setText(context.getResources().getString(R.string.text_app_update_dialog_current_version, ApkUtil.getAppVersionName(context)));
            if (false) {
                btnNot.setVisibility(View.GONE);
                lineView.setVisibility(View.GONE);
                btnUpdate.setBackgroundResource(R.drawable.material_dialog_button_normal);
            } else {
                btnNot.setVisibility(View.VISIBLE);
                lineView.setVisibility(View.VISIBLE);
                btnUpdate.setBackgroundResource(R.drawable.material_dialog_button_yes);
            }
        }

        btnNot.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                UpdateAppDialog.this.dismiss();
            }
        });

        btnUpdate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                UpdateAppDialog.this.dismiss();
                if (isAPKExist && isFileSize) {
                    installAPK(context, new File(GeneralUtil.getAPKSaveFilePath(context, isnew)));
                    return;
                }
                if (NetWorkUtil.getCurrentNetWorkStatus(context) != 1) {
                    showNetDialog(context, isnew,url);
                    return;
                }
                Intent intent = new Intent(context, UpdateAppService.class);
                intent.putExtra(Constants.ACTIVITY_PUTEXTRA_APK_URL, url);
                intent.putExtra(Constants.ACTIVITY_PUTEXTRA_APK_VERSION, isnew);
                context.startService(intent);
            }
        });
    }

    private void showNetDialog(final Context context, final String isnew,final String  url) {
        final MaterialDialog mMaterialDialog = new MaterialDialog(context);
        mMaterialDialog
                .setMessage(
                        context.getResources().getString(R.string.text_app_update_dialog_download_not_wifi))
                .setPositiveButton(
                        context.getResources().getString(R.string.text_app_update_dialog_continuance_download),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mMaterialDialog.dismiss();
                                Log.i("tag", "item.download_url");
                                Intent intent = new Intent(context, UpdateAppService.class);
                                intent.putExtra(Constants.ACTIVITY_PUTEXTRA_APK_URL, url);
                                intent.putExtra(Constants.ACTIVITY_PUTEXTRA_APK_VERSION, isnew);
                                context.startService(intent);

                            }
                        })
                .setNegativeButton(
                        context.getResources().getString(R.string.text_app_update_dialog_cancel_download),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mMaterialDialog.dismiss();
                            }
                        });

        mMaterialDialog.show();
    }



    private void installAPK(Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(context,"com.hhxx.jyhw.fileProvider",apkFile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri,"application/vnd.android.package-archive");
        }else{
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

}
